package test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author Marioszk
 * 反转字符串中的单词，剔除其中一个或多个空格
 * lettcode 151
 */
public class ReverseWords_反转字符串中的单词 {
    public static void main(String[] args) {
        String str = "a good   example";
        System.out.println(reverseWords(str));
    }

    public static String reverseWords(String s) {
        if (s == null) {
            return "";
        }
        String str = s.trim();
        String[] arr = str.split(" ");
        StringBuilder sb = new StringBuilder();
        for (int i = arr.length - 1; i >= 0; i--) {
            if ("".equals(arr[i])) {
                continue;
            }
            if (i != 0) {
                sb.append(arr[i]).append(" ");
            } else {
                sb.append(arr[i]);
            }
        }
        return sb.toString();
    }

    public String reverseWords2(String s) {
        // 除去开头和末尾的空白字符
        s = s.trim();
        // 正则匹配连续的空白字符作为分隔符分割
        List<String> wordList = Arrays.asList(s.split("\\s+"));
        Collections.reverse(wordList);
        return String.join(" ", wordList);
    }
}
